<template>
  <!-- 用户管理 -->
  <div class="userMannage">
    <ContentWrap>
      <FormContainer :column="4">
        <el-form ref="form" :model="formData" :rules="formRules" label-width="80px">
          <el-form-item prop="id" label="用户">
            <SearchSelectPicker
              url="/call-center/api/v1/staffInfo/page"
              placeholder="请选择"
              lable-name="staffName"
              value-name="accountNo"
              :value.sync="accountNo"
              @selectChange="(val)=>{val?formData.id = val.id:formData.id=''}"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="accountNo" label="账号">
            <el-input v-model="formData.accountNo" placeholder="请输入账号" clearable />
          </el-form-item>
          <el-form-item prop="staffCode" label="员工编号">
            <el-input v-model="formData.staffCode" placeholder="请输入员工编号" clearable />
          </el-form-item>
          <el-form-item prop="deptNo" label="组织">
            <el-select v-model="formData.deptNo" filterable clearable placeholder="请选择组织">
              <el-option
                v-for="item in departmentOption"
                :key="item.id"
                :label="item.deptName"
                :value="item.deptNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="groupNo" label="业务组">
            <el-select v-model="formData.groupNo" filterable clearable placeholder="请选择业务组">
              <el-option
                v-for="item in businessOptions"
                :key="item.id"
                :label="item.groupName"
                :value="item.groupNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="skillNo" label="技能队列">
            <el-select v-model="formData.skillNo" filterable clearable placeholder="请选择技能队列">
              <el-option
                v-for="item in skillGroupOption"
                :key="item.id"
                :label="item.skillName"
                :value="item.skillNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="state" label="状态">
            <el-select v-model="formData.state" clearable>
              <el-option label="启用" value="1" />
              <el-option label="离职" value="-1" />
              <el-option label="停用" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item prop="platformNo" label="平台工号">
            <el-input v-model="formData.platformNo" placeholder="请输入平台工号" clearable />
          </el-form-item>
          <el-form-item prop="callPlatform" label="话务平台">
            <SelectForDict
              dict-type-code="CALL_PLATFORM"
              app-code="call-center"
              :code.sync="formData.callPlatform"
              placeholder="请选择话务平台"
            ></SelectForDict>
          </el-form-item>
          <el-form-item show more align="right">
            <Button @click="resetHandle('form')">重置</Button>
            <Button type="primary" :loading="loading" enter @click="queryHandle('form')">查询</Button>
          </el-form-item>
        </el-form>
      </FormContainer>
      <div class="button-container" style="padding-top: 0">
        <DistributionBtn
          text="组织"
          type="1"
          :selected="selectedAry"
          @confrim="orgFunc"
        />
        <DistributionBtn
          text="业务组"
          type="2"
          :selected="selectedAry"
          @confrim="businessFunc"
        />
        <DistributionBtn
          text="技能队列"
          type="3"
          :selected="selectedAry"
          @confrim="skillFunc"
        />
        <DistributionBtn
          text="平台工号"
          type="4"
          :selected="selectedAry"
          @confrim="platformNoFunc"
        />
        <DistributionBtn
          text="话务平台"
          type="5"
          :selected="selectedAry"
          @confrim="callPlatformFunc"
        />
      </div>
      <table-box
        ref="table"
        no-request
        show-index
        show-selection
        :selected-arry.sync="selectedAry"
        :other-filters="otherFilters"
        :table-config="tableConfig"
        @data-change="loading = false"
        @selection-change="selectionChange"
      ></table-box>
    </ContentWrap>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import FormContainer from '@/components/FormContainer'
import Button from '@/components/Button'
import DistributionBtn from './components/DistributionBtn'
import SearchSelectPicker from '@/components/SearchSelectPicker'
import SelectForDict from '@/components/SelectForDict'
import { getDepartmentInfo, postMembersDepts, deleteMembersByAccount } from '@/api/department'
import { getBusinessAll, postBusinessMembers, deleteBusinessByAccount } from '@/api/business'
import { getSkillGroup, postSkillMembers, deleteSkillByAccount } from '@/api/skillGroup'
import { updateStaffInfo, updateCallPlatform } from '@/api/staffInfo'
import { filtersRaw } from '@/utils'
export default {
  name: 'SysUser',
  components: {
    ContentWrap,
    FormContainer,
    Button,
    DistributionBtn,
    SearchSelectPicker,
    SelectForDict
  },
  data() {
    return {
      accountNo: '',
      formData: {
        id: '',
        accountNo: '',
        staffCode: '',
        deptNo: '',
        groupNo: '',
        skillNo: '',
        sourceType: '',
        transferPhone: '',
        state: '',
        platformNo: '',
        callPlatform: ''
      },
      selectedAry: [],
      businessOptions: [],
      skillGroupOption: [],
      departmentOption: [],
      formRules: {},
      loading: false,
      otherFilters: [],
      paramsRaw: {},
      tableConfig: {
        interfacePath: '/call-center/api/v1/staffInfo/page',
        pageFlag: true,
        hideFuncBar: true,
        sort: 'platformNo',
        order: 'desc',
        // 表格字段动态配置
        setting: [
          {
            prop: 'staffName',
            label: '用户',
            width: 110,
            formatData: val => {
              return `${val.staffName}(${val.accountNo})`
            }
          },
          {
            prop: 'staffName',
            label: '用户姓名',
            width: 100,
            align: 'center'
          },
          {
            prop: 'accountNo',
            label: '账号',
            minWidth: 120
          },
          {
            prop: 'staffCode',
            label: '员工编号',
            minWidth: 120
          },
          {
            prop: 'organization',
            label: 'QUP组织关系',
            minWidth: 120,
            formatData: (val) => { return val.organization ? val.organization : '--' }
          },
          {
            prop: 'deptName',
            label: '组织',
            minWidth: 120,
            formatData: (val) => {
              if (val.deptName) return val.deptName
              return '--'
            }
          },
          {
            prop: 'groupName',
            label: '业务组',
            minWidth: 120,
            formatData: (val) => {
              if (val.groupName) return val.groupName
              return '--'
            }
          },
          {
            prop: 'skillName',
            label: '技能队列',
            minWidth: 120,
            formatData: (val) => {
              if (val.skillName) return val.skillName
              return '--'
            }
          },
          {
            prop: 'state',
            label: '状态',
            width: '80',
            formatData: val => {
              if (Number(val.state) === 1) return '启用'
              if (Number(val.state) === -1) return '离职'
              if (Number(val.state) === 0) return '停用'
              return '--'
            }
          },
          {
            prop: 'platformNo',
            label: '平台工号',
            minWidth: 100,
            formatData: val => {
              if (val.platformNo) return val.platformNo
              return '--'
            }
          },
          {
            prop: 'callPlatform',
            label: '呼叫平台',
            minWidth: 100,
            propEnum: {
              domainCode: 'marketing',
              appCode: 'call-center',
              dictTypeCode: 'CALL_PLATFORM'
            }
          }
        ]
      }
    }
  },
  created() {
  },
  mounted() {
    this.initBusinessOption()
    this.initSkillGroupInfo()
    this.initDepartmentInfo()
  },
  methods: {
    // 根据条件查询
    queryHandle(formName) {
      const list = []
      const eq = ['id', 'accountNo', 'staffCode', 'deptNo', 'groupNo', 'skillNo', 'state', 'platformNo', 'sourceType', 'callPlatform']
      for (const [k, v] of Object.entries(this.formData)) {
        if (v === undefined || v === null || v === '' || (typeof v === 'object' && Object.keys(v).length <= 0)) {
          continue
        }
        if (eq.includes(k)) {
          list.push(filtersRaw(k, v, '='))
        } else {
          list.push(filtersRaw(k, v, 'like'))
        }
      }
      this.otherFilters = list
      this.$nextTick(() => {
        this.$refs.table.initTableData()
      })
    },
    /**
     * 获取组类别
     */
    initBusinessOption() {
      getBusinessAll().then(res => {
        if (res.success === 1) {
          this.businessOptions = res.data
        }
      })
    },
    // 初始化技能队列
    initSkillGroupInfo() {
      getSkillGroup().then(res => {
        if (res.success === 1) {
          this.skillGroupOption = res.data
        }
      })
    },
    // 初始化部门
    initDepartmentInfo() {
      getDepartmentInfo().then(res => {
        if (res.success === 1) {
          this.departmentOption = res.data
        }
      })
    },
    // 重置表单
    resetHandle(formName) {
      this.formData.id = ''
      this.$refs[formName].resetFields()
    },
    // 组织分配确认
    orgFunc(data) {
      if (Array.isArray(this.selectedAry) && this.selectedAry.length) {
        const { accountNo } = this.selectedAry[0]
        const { newArr, oldArr } = data
        const oldDeptIdArr = oldArr.map(list => {
          return list.id
        })
        const addDeptIdArr = newArr.map(list => {
          return list.id
        })
        const deleteDeptIdArr = []
        oldDeptIdArr.forEach(id => {
          if (addDeptIdArr.indexOf(id) === -1) deleteDeptIdArr.push(id)
        })
        if (addDeptIdArr.length > 1) {
          this.$message({
            message: '不能同时分配多个组织',
            type: 'warning'
          })
          return
        }
        if (deleteDeptIdArr.length) {
          deleteMembersByAccount(accountNo, deleteDeptIdArr).then(res => {
            if (res.success === 1) {
              postMembersDepts(accountNo, addDeptIdArr).then(res => {
                if (res.success === 1) {
                  this.$nextTick(() => {
                    this.$refs.table.initTableData('onPage')
                  })
                  this.$message({
                    message: '组织分配成功',
                    type: 'success'
                  })
                }
              })
            }
          }, () => {
            this.$message({
              message: '组织分配失败',
              type: 'warning'
            })
          })
        } else {
          postMembersDepts(accountNo, addDeptIdArr).then(res => {
            if (res.success === 1) {
              this.$nextTick(() => {
                this.$refs.table.initTableData('onPage')
              })
              this.$message({
                message: '组织分配成功',
                type: 'success'
              })
            }
          })
        }
      }
    },
    // 业务组分配确认
    businessFunc(data) {
      if (Array.isArray(this.selectedAry) && this.selectedAry.length) {
        const { accountNo } = this.selectedAry[0]
        const { newArr, oldArr } = data
        const oldGroupIdArr = oldArr.map(list => {
          return list.id
        })
        const addGroupIdArr = newArr.map(list => {
          return list.id
        })
        const deleteGroupIdArr = []
        oldGroupIdArr.forEach(id => {
          if (addGroupIdArr.indexOf(id) === -1) deleteGroupIdArr.push(id)
        })
        if (deleteGroupIdArr.length) {
          deleteBusinessByAccount(accountNo, deleteGroupIdArr).then(res => {
            if (res.success === 1) {
              postBusinessMembers(accountNo, addGroupIdArr).then(res => {
                if (res.success === 1) {
                  this.$nextTick(() => {
                    this.$refs.table.initTableData('onPage')
                  })
                  this.$message({
                    message: '业务组分配成功',
                    type: 'success'
                  })
                }
              })
            }
          }, () => {
            this.$message({
              message: '业务组分配失败',
              type: 'warning'
            })
          })
        } else {
          postBusinessMembers(accountNo, addGroupIdArr).then(res => {
            if (res.success === 1) {
              this.$nextTick(() => {
                this.$refs.table.initTableData('onPage')
              })
              this.$message({
                message: '业务组分配成功',
                type: 'success'
              })
            }
          })
        }
      }
    },
    // 技能队列分配确认
    skillFunc(data) {
      if (Array.isArray(this.selectedAry) && this.selectedAry.length) {
        const { accountNo } = this.selectedAry[0]
        const { newArr, oldArr } = data
        const oldSkillIdArr = oldArr.map(list => {
          return list.id
        })
        const addSkillIdArr = newArr.map(list => {
          return list.id
        })
        const deleteSkillIdArr = []
        oldSkillIdArr.forEach(id => {
          if (addSkillIdArr.indexOf(id) === -1) deleteSkillIdArr.push(id)
        })
        if (deleteSkillIdArr.length) {
          deleteSkillByAccount(accountNo, deleteSkillIdArr).then(res => {
            if (res.success === 1) {
              postSkillMembers(accountNo, addSkillIdArr).then(res => {
                if (res.success === 1) {
                  this.$nextTick(() => {
                    this.$refs.table.initTableData('onPage')
                  })
                  this.$message({
                    message: '技能队列分配成功',
                    type: 'success'
                  })
                }
              })
            }
          }, () => {
            this.$message({
              message: '技能队列分配失败',
              type: 'success'
            })
          })
        } else {
          postSkillMembers(accountNo, addSkillIdArr).then(res => {
            if (res.success === 1) {
              this.$nextTick(() => {
                this.$refs.table.initTableData('onPage')
              })
              this.$message({
                message: '技能队列分配成功',
                type: 'success'
              })
            }
          })
        }
      }
    },
    // 平台工号分配
    platformNoFunc(data) {
      if (Array.isArray(this.selectedAry) && this.selectedAry.length) {
        const { id } = this.selectedAry[0]
        updateStaffInfo(id, data.platformNo).then(res => {
          if (res.success === 1) {
            this.$refs.table.initTableData('onPage')
            this.$message({
              message: '平台工号分配成功',
              type: 'success'
            })
          }
        })
      }
    },
    callPlatformFunc(callPlatform, ids) {
      updateCallPlatform(callPlatform, ids).then(res => {
        this.$refs.table.initTableData('onPage')
        this.$message.success('话务平台更新成功!')
      })
    },
    handleRefresh() {
      this.$refs.table.initTableData('onPage')
    },
    selectionChange(val) {
      this.selectedAry = val
    }
  }
}
</script>
<style lang='scss' module>
</style>
